package cn.itsource.xhy.pet.controller;

import cn.itsource.xhy.org.domain.Employee;
import cn.itsource.xhy.org.domain.Shop;
import cn.itsource.xhy.org.service.IShopService;
import cn.itsource.xhy.pet.domain.Pet;
import cn.itsource.xhy.pet.query.PetQuery;
import cn.itsource.xhy.pet.service.IPetService;
import cn.itsource.xhy.utils.AjaxResult;
import cn.itsource.xhy.utils.LoginContext;
import cn.itsource.xhy.utils.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    private IPetService petService;

    @Autowired
    private IShopService shopService;


    @PostMapping
    public QueryResult<Pet> queryPage(@RequestBody PetQuery petQuery, HttpServletRequest request){
        // 获取当前登录用户
        Employee employee = (Employee) LoginContext.getObject(request);
        // 查询到店铺
        Shop shop = shopService.loadByAdminId(employee.getId());
        petQuery.setShopId(shop.getId());
        return petService.queryPage(petQuery);
    }

    @PostMapping("/front")
    public QueryResult<Pet> queryPageByFront(@RequestBody PetQuery petQuery, HttpServletRequest request){
        return petService.queryPage(petQuery);
    }

    @GetMapping("/detail/{id}")
    public Pet findByPetId(@PathVariable("id") Long id){
        return petService.findByPetId(id);
    }

    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Pet pet,HttpServletRequest request){
        try {
            // 获取当前登录用户
            Employee employee = (Employee) LoginContext.getObject(request);
            // 查询到店铺
            Shop shop = shopService.loadByAdminId(employee.getId());
            pet.setShop_id(shop.getId());
            if(pet.getId()==null){
                petService.save(pet);
            } else {
                petService.update(pet);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败" + e.getMessage());
        }
    }

    @PatchMapping("/onSale")
    public AjaxResult onSale(@RequestBody Long[] ids){
        try {
            petService.onSale(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }

    @PatchMapping("/downSale")
    public AjaxResult downSale(@RequestBody Long[] ids){
        try {
            petService.downSale(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }
}
